<?php

/**
 * This is the model class for table "service".
 *
 * The followings are the available columns in table 'service':
 * @property integer $id
 * @property string $name_en
 * @property string $name_th
 * @property string $short_description_en
 * @property string $short_description_th
 * @property string $description_en
 * @property string $description_th
 * @property string $slug
 * @property string $status
 * @property string $thumbnail_path
 *
 * The followings are the available model relations:
 * @property ServiceTopic[] $serviceTopics
 */
class Service extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Service the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'service';
	}
	
  public function beforeSave() 
  {
    if($this->isNewRecord)
    {           
      $this->status = 'A';
    }
    return parent::beforeSave();
  }	

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name_en', 'required'),
			array('name_en, name_th, slug, thumbnail_path', 'length', 'max'=>100),
			array('short_description_en, short_description_th', 'length', 'max'=>255),
			array('status', 'length', 'max'=>1),
			//array('status','in','range'=>array('A','I','D'),'allowEmpty'=>false),
			array('description_en, description_th', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name_en, name_th, short_description_en, short_description_th, description_en, description_th, slug, status, thumbnail_path', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'serviceTopics' => array(self::HAS_MANY, 'ServiceTopic', 'service_id'),
			'serviceTopicsCount'=>array(self::STAT, 'ServiceTopic', 'service_id', 'condition'=>'status!="D"'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name_en' => 'Name En',
			'name_th' => 'Name Th',
			'short_description_en' => 'Short Description En',
			'short_description_th' => 'Short Description Th',
			'description_en' => 'Description En',
			'description_th' => 'Description Th',
			'slug' => 'Slug',
			'status' => 'Status',
			'thumbnail_path' => 'Thumbnail Path',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name_en',$this->name_en,true);
		$criteria->compare('name_th',$this->name_th,true);
		$criteria->compare('short_description_en',$this->short_description_en,true);
		$criteria->compare('short_description_th',$this->short_description_th,true);
		$criteria->compare('description_en',$this->description_en,true);
		$criteria->compare('description_th',$this->description_th,true);
		$criteria->compare('slug',$this->slug,true);
		$criteria->compare('status',$this->status,true);
		$criteria->compare('thumbnail_path',$this->thumbnail_path,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
  public function behaviors(){
    return array(
      'sluggable' => array(
        'class'=>'ext.SluggableBehavior.SluggableBehavior',
        'columns' => array('name_en'),
        'unique' => true,
        'update' => true,
      ),
    );
  }	

  //virtual field
  public function getShort_description()
  {
    $ret = $this->short_description_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->short_description_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->short_description_en;
      }
    }

    return $ret;
  }

  public function getName()
  {
    $ret = $this->name_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->name_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->name_en;
      }
    }

    return $ret;
  }	
  
  public function saveThumbnail()
  {
    $path = '/uploads/images/service/';

    //save image
    $image = CUploadedFile::getInstanceByName('Service[thumbnail_path]');

    if (isset($image->name) && $image->saveAs(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name)) {
      
      //edit file
      $file = Yii::app()->image->load(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name);

      $photoName = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789'),0,12);

      //$file->resize(776, 437, Image::WIDTH);
      //$file->save(Yii::getPathOfAlias('webroot').$path.$photoName.'.jpg');
      $file->resize(263, 148, Image::WIDTH);
      $file->save(Yii::getPathOfAlias('webroot').$path. $photoName.'.jpg');
      //unlink(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name);
      $ret = $path.$photoName.'.jpg';
      $this->thumbnail_path = $ret;
    }else {
      if (!empty($this->id)) {
        $this->thumbnail_path = $this->findByPk($this->id)->thumbnail_path;
      }else {
        $this->thumbnail_path = null;
      }
    }
    return $this->thumbnail_path;

  }
  
  public function getCountPhoto() 
  {
    return Slide::model()->count(array(
      'condition'=>'model_name=:name AND model_id=:modelId', 
      'params'=>array('name' => 'service',':modelId'=>$this->id)
    ));     
  }
	
}